<?php

declare(strict_types=1);

namespace app\api\controller;

use think\exception\ValidateException;
use think\facade\View;
use think\response\Json;
use app\common\model\Order as OrderModel;
use app\common\model\Evaluate;
use app\common\tool\Result;
use app\common\model\SpecItem;
use app\common\model\LntegralSpecItem;
use app\common\model\OrderProduct;
use app\common\model\OrderRefund;
use app\common\controller\Config;



class Order extends Base
{
    //获取订单信息
    public function index()
    {
        $temporary = OrderModel::getTemporary($this->user);

        if (empty($temporary) || empty($temporary['products'])) {
            return Result::fail('加载失败，未查询到待提交的订单', '', -6);
        }
        return Result::success('获取成功！', $temporary);
    }
    //修改
    public function submit()
    {
        $param = $this->request->post();
        return Result::fastReturn(OrderModel::submit($param, $this->user, $this->token));
    }
    //提交订单
    public function payment()
    {
        $coupon_open = Config::lists()['coupon_open'];
        $info = OrderModel::getNowOrder($this->user->id);
        if ($info['code'] != 1) {
            return Result::fail('加载失败，未查询到待支付的订单', '', -6);
        }
        $result['total'] = $info['result']['real_amount'];

        $result['order_id'] = $info['result']['id'];
        $result['coupon_open'] = intval($coupon_open);


        // $result['method'] = [
        //     [
        //         'title' => '微信支付',
        //         'pay_way' => 'wechat',
        //         'icon' => handleImg('/static/index/img/wechat.png')
        //     ],
        //     [
        //         'title' => '电子币',
        //         'pay_way' => 'currency',
        //         'icon' => handleImg('/static/index/img/currency.png')
        //     ],
        //     [
        //         'title' => '奖金',
        //         'pay_way' => 'bonus',
        //         'icon' => handleImg('/static/index/img/bonus.png')
        //     ],
        // ];
        // $result['is_pay_password'] = 1;
        return Result::success('获取成功！',  $result);
    }
    //提交订单
    public function confirmPayment(): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'ConfirmPayment');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
        return Result::fastReturn(OrderModel::confirmPayment($param, $this->user));
    }

    //代付
    public function payAgent(): Json
    {
        $param = $this->request->post();
        try {
            return Result::fastReturn(OrderModel::payAgent($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }

    public function my_order()
    {
        return View::fetch();
    }
    //订单详情
    public function my_order_details()
    {
        $id = $this->request->param('id');
        $info = OrderModel::where(['id' => $id, 'is_del' => 0])->find();
        if ($info->getData('status') == 5) {
            OrderModel::where(['id' => $id, 'is_del' => 0])->update(['is_read' => 1]);
        }
        if ($info->uid == $this->user->id) {
            $info->myorder = 1;
        } else {
            $info->myorder = 0;
        }
        if (empty($info)) {
            return Result::fail('未查询到相关订单');
        }
        if ($info->getData('status') < 3) {
            $info->addressData = [
                'receiver' => $info->address->nickname,
                'receiver_tel' => $info->address->tel,
                'province' => $info->address->p->title,
                'city' => $info->address->c->title,
                'district' => $info->address->d->title,
                'details' => $info->address->details
            ];
        } else {
            $info->addressData = [
                'receiver' => $info->receiver,
                'receiver_tel' => $info->receiver_tel,
                'province' => $info->p->title,
                'city' => $info->c->title,
                'district' => $info->d->title,
                'details' => $info->address_details
            ];
            $info->expressData = [
                'express_id' => $info->express_id,
                'express_code' => $info->express_code,
                //'express_title' => $info->express->title,
            ];
        }

        $info->order_status = $info->getData('status');
        $info->productsData = $info->products;
        $date = [
            'pay_time',
            'receipt_time',
            'comment_time',
            'finish_time',
            'refund_time',
            'cancel_time',
            'remind_time'
        ];
        foreach ($date as $v) {
            $info->$v = $info->$v ? date('Y-m-d H:i:s', intval($info->$v)) : '';
        }
        $unset = [
            'receiver',
            'receiver_tel',
            'province',
            'city',
            'district',
            'town',
            'address_details',
            'address',
            'uid',
            'address_id',
            'is_del',
            'order_type',
            'express',
            'express_id',
            'express_code',
            'update_time',
            'p',
            'c',
            'd',
            't',
            'products'
        ];
        foreach ($unset as $v) {
            unset($info->$v);
        }

        return Result::success('获取成功！', $info);
    }

    //获取订单列表
    public function getList()
    {
        $param = $this->request->param();
        if (isset($param['type']) && $param['type']) {
            $map = ['uid' => $this->user->id, 'status' => $param['type'], 'is_del' => 0];
        } else {
            $map = ['uid' => $this->user->id, 'is_del' => 0];
        }
        $list = OrderModel::getPageList($map, 'id,sn,pay_way,status,create_time,shoptype,total_amount,real_amount,is_remind', $param['page'], 20, false, ['products']);
        foreach ($list['data'] as $k => $v) {
            $v['order_status'] = $v->getData('status');
            $v['shoptype_name'] = $v['shoptype'] == 'shop' ? '普通订单' : ($v['shoptype'] == 'seckill' ? '秒杀订单' : '积分订单');
            $list['data'][$k] = $v;
        }
        return Result::success('获取成功！', $list);
    }
    //获取分销订单列表
    public function order_form()
    {
        if ($this->user->is_place == 0) {
            return Result::fail('您不是分销商');
        }
        $param = $this->request->param();
        if (isset($param['type']) && $param['type']) {
            $map = ['commission_uid1|commission_uid2' => $this->user->id, 'status' => $param['type'], 'is_del' => 0];
        } else {
            $map = ['commission_uid1|commission_uid2' => $this->user->id, 'is_del' => 0];
        }
        $list = OrderModel::getPageList($map, 'id,sn,uid,pay_way,status,create_time,total_amount,is_remind', $param['page'], 20, false, ['products', 'user']);
        foreach ($list['data'] as $k => $v) {
            foreach ($v['products'] as $kk => $vv) {
                if ($vv['spec'] != '') {
                    $spce = explode('-', $vv['spec']);
                    $Specname = SpecItem::whereIn('id', $spce)->column('name');
                    $vv['specname'] = implode('-', $Specname);
                } else {
                    $vv['specname'] = '默认';
                }
                $v['products'][$kk] = $vv;
            }
        }
        return Result::success('获取成功！', $list);
    }

    //修改订单状态
    public function edit()
    {
        $param = $this->request->post();
        try {
            return Result::fastReturn(OrderModel::edit($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
    //订单评价
    public function addEvaluatet()
    {
        $param = $this->request->post();
        try {

            //$this->validate($param, 'Evaluate');
            return Result::fastReturn(Evaluate::addEvaluatet($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
    //评价商品
    public function getOrderProduct()
    {
        $param = $this->request->get();
        $order = OrderModel::where(['id' => $param['id'], 'is_del' => 0])->find();
        if (!empty($order)) {
            if ($order->getData('status') == 4) {
                if ($order->uid == $this->user->id) {
                    $map[] = ['order_id', '=', $param['id']];
                    $OrderProduct = OrderProduct::where($map)->select();
                    foreach ($OrderProduct as $k => $v) {
                        $v['pronum'] = 0;
                        $v['images'] = [];
                        $v['imageslist'] = [];
                        $v['content'] = '';
                        $OrderProduct[$k] = $v;
                    }
                    $list['list'] = $OrderProduct;
                    $list['msnum'] = 0;
                    $list['wlnum'] = 0;
                    $list['fwnum'] = 0;
                    return Result::success('获取成功！', $list);
                } else {
                    return Result::fail('非本人订单不可评论！');
                }
            } else {
                return Result::fail('该订单已评价！');
            }
        } else {
            return Result::fail('该订单不存在！');
        }
    }
    //我的评价和商品评价
    public function getEvaluateList()
    {
        $param = $this->request->get();
        if (isset($param['product_id']) && !empty($param['product_id']) && $param['product_id'] != 0) {
            $map[] = ['product_id', '=', $param['product_id']];
        } else {
            $map[] = ['uid', '=', $this->user->id];
        }
        $list = Evaluate::getPageList($map, '*', $param['page'], 20, false, ['user', 'product']);
        foreach ($list['data'] as $k => $v) {
            if (!empty($v['images'])) {
                $imageslist = explode(',', $v['images']);
                foreach ($imageslist as $kk => $vv) {
                    $imageslists[$kk] = handleImg($vv);
                }
                $v['imageslist'] = $imageslists;
            } else {
                $v['imageslist'] = [];
            }
            //$v['user']['nickname']='匿名用户';
            $list['data'][$k] = $v;
        }
        return Result::success('获取成功！', $list);
    }
    //获取团队订单
    public function getTeamOrderList()
    {
        $status = [4, 5];
        $param = $this->request->param();
        $page = $param['page'];
        $num = 20;
        if ($page == 1) {
            $start = 0;
        } else {
            $start = $page * $num - $num;
        }
        $list = OrderModel::whereIn('status', $status)->where(['commission_uid1|commission_uid2' => $this->user->id, 'is_del' => 0])->with(['user'])->limit($start, $num)->select();
        foreach ($list as $k => $v) {
            if ($v['commission_uid1'] == $this->user->id) {
                $v['commission'] = $v['commission1'];
                $v['commissiontitle'] = '一级分销';
            }
            if ($v['commission_uid2'] == $this->user->id) {
                $v['commission'] = $v['commission2'];
                $v['commissiontitle'] = '二级分销';
            }
            $v['user']['mobiles'] = substr_replace($v['user']['mobile'], '****', 3, 4);
            $v['times'] = date('Y-m-d', strtotime($v['create_time']));
            $list[$k] = $v;
        }
        return Result::success('获取成功！', $list);
    }
    //退款申请
    public function order_refund()
    {

        $param = $this->request->post();
        try {
            $this->validate($param, 'OrderRefund');
            return Result::fastReturn(OrderModel::order_refund($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }

    //退款售后列表
    public function getRefundList()
    {
        $param = $this->request->param();
        $page = $param['page'];
        $num = 20;
        if ($page == 1) {
            $start = 0;
        } else {
            $start = $page * $num - $num;
        }
        $list = OrderRefund::where(['uid' => $this->user->id, 'is_del' => 0])->with(['user', 'order'])->limit($start, $num)->select();
        foreach ($list as $k => $v) {
            $product = OrderProduct::where(['order_id' => $v['order_id']])->select();
            foreach ($product as $kk => $vv) {
                if ($vv['spec'] != '') {
                    $spce = explode('-', $vv['spec']);
                    $Specname = SpecItem::whereIn('id', $spce)->column('name');
                    $vv['specname'] = implode('-', $Specname);
                } else {
                    $vv['specname'] = '默认';
                }
                $product[$kk] = $vv;
            }
            $v['product'] = $product;
            $list[$k] = $v;
        }
        return Result::success('获取成功！', $list);
    }
    //获取快递公司
    public function  getLogistics()
    {
        $list = \app\common\model\Express::where(['status' => 1, 'is_del' => 0])->select();
        foreach ($list as $k => $v) {
            $v['value'] = $v->id;
            $v['text'] = $v->title;
            $list[$k] = $v;
        }
        return Result::success('获取成功！', $list);
    }
    //提交物流信息
    public function uploadLogistics()
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'UploadLogistics');
            return Result::fastReturn(OrderRefund::uploadLogistics($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
    //获取退款详情
    public function refund_detail()
    {
        $param = $this->request->param();
        $list = OrderRefund::where(['id' => $param['id'], 'is_del' => 0])->with(['user', 'order'])->find();
        foreach ($list as $k => $v) {
            $v->order->refund_time = 11111;
            $list[$k] = $v;
        }
        $product = OrderProduct::where(['order_id' => $list['order_id']])->select();
        foreach ($product as $kk => $vv) {
            if ($vv['spec'] != '') {
                $spce = explode('-', $vv['spec']);
                if ($vv['shoptype'] == 'lntegra') {
                    $Specname = LntegralSpecItem::whereIn('id', $spce)->column('name');
                } else {
                    $Specname = SpecItem::whereIn('id', $spce)->column('name');
                }
                $vv['specname'] = implode('-', $Specname);
            } else {
                $vv['specname'] = '默认';
            }
            $product[$kk] = $vv;
        }
        $list['product'] = $product;
        return Result::success('获取成功！', $list);
    }
}
